<?php
/**
 * @园区类
 * 1、园区列表
 * 2、园区详情
 */

namespace app\admin\controller;

use app\common\controller\HomeCommon;
use app\common\model\Label;
use think\Cache;
use think\Config;
use think\Controller;
use think\Db;
use think\Request;
use think\View;

class Park extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 添加园区
     * @param Request $request
     * @return mixed
     */
    public function add(Request $request)
    {
        if ($request->isPost()){
            $data=$request->post();
            /****city_str*****/
            $data['city_id']=$request->param('city_id',0,'intval');
            $data['area_id']=$request->param('area_id',0,'intval');
            $city=array($data['province_id'],$data['city_id'],$data['area_id']);
            $city_str=[];
            $cityModel=db('city');
            foreach ($city as $id){
                if (!empty($id)){
                    $name=$cityModel->where('id',$id)->value('city_name as name');
                    $city_str[]=compact('id','name');
                }
            }
            $city_name=array_column($city_str,'name');
            $data['city']=$data['province']= isset($city_name[0]) ? $city_name[0] : '';
            $data['p_city']=isset($city_name[1]) ? $city_name[1] : '';
            $data['district']=isset($city_name[2]) ? $city_name[2] : '';
            /****industry_str*****/
            $industry_str=[];
            $industry_ids=[];
            $industry_data=$request->post()['industry'];
            $industryModel=db('industry');
            foreach ($industry_data as $id){
                if ($id){
                    $name=$industryModel->where('id',$id)->value('industry_name as name');
                    $industry_str[]=compact('id','name');
                    array_push($industry_ids,$id);
                }
            }
            /****chain****/
            $chain_data=$request->post()['chain'];
            $chains=[];
            foreach ($chain_data as $chain_id){
                if ($chain_id){
                    array_push($chains,$chain_id);
                }
            }

            $data['city_str']=serialize($city_str);
            $data['prime_mover_industry']=implode('@',array_column($industry_str,'name'));
            $data['identification']=uniqid('xd');
            $data['status']=1;

            unset($data['chain'],$data['industry']);
            $chainInsert=[];
            $industryInsert=[];
            Db::startTrans();
            try {
                /****主表****/
                $park_id=Db::table('yd_parks')->insertGetId($data);
                /****chain****/
                foreach ($chains as $k=>$id){
                    $chainInsert[$k]['park_id']=$park_id;
                    $chainInsert[$k]['chain_id']=$id;
                    $chainInsert[$k]['status']=1;
                }
                Db::table('yd_parks_chain')->insertAll($chainInsert);
                /****industry****/
                foreach ($industry_ids as $k=>$id){
                    $industryInsert[$k]['park_id']=$park_id;
                    $industryInsert[$k]['industry_id']=$id;
                    $industryInsert[$k]['status']=1;
                }
                Db::table('yd_parks_industry')->insertAll($industryInsert);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $msg  = "File：" . $e->getFile() . "\n";
                $msg .= "Line：" . $e->getLine() . "\n";
                $msg .= "Message：" . $e->getMessage() . "\n";
                var_dump($msg);
                // 回滚事务
                Db::rollback();
                $this->error('添加失败','add');
            }
            $this->success('添加成功','park_list');
        }

        //产业链 城市 行业 list
        $label =new Label();
        $city=$label->city_list();
        $chain=$label->chain(0);
        $industry=$label->industry(0);
        $this->assign('chain',$chain);
        $this->assign('city',$city);
        $this->assign('industry',$industry);

        return $this->fetch('add');
    }

    /**
     * 园区列表
     */
    public function park_list(Request $request)
    {
        $park_name=$request->param('park_name','','trim');
        /***园区基本信息***/
        $park_obj=db('parks a')
            ->field('a.id,a.park_name,a.prime_mover_industry,a.city_str')
            ->where(['a.status'=>1])
            ->order('id','desc');
        /***园区名称***/
        if (!empty($park_name)){
            $park_obj->where('park_name','like','%'.$park_name.'%');
        }
        $park=$park_obj->paginate(['query' => request()->param()]);
        $this->view->assign('page', $park->render());
        $park= $park->toArray();
        foreach ($park['data'] as &$value){
            $chain_id=db('parks_chain')->where(['status'=>1,'park_id'=>$value['id']])->min('chain_id');
            $value['chain_name']=db('chain')->where(['status'=>1,'id'=>$chain_id])->value('chain_name');
            $city_str=unserialize($value['city_str']) ? unserialize($value['city_str']) : [];
            $value['city_str']=implode('@',array_column($city_str,'name'));
        }

        $this->view->assign('park', $park);
        return $this->fetch('park_list');
    }

    /**
     * 园区详情
     * @return mixed
     */
    public function detail()
    {
        $id=$this->request->get('id',0,'intval');
        $park=db('parks')
            ->where(['status'=>1,'id'=>$id])
            ->find();
        if (empty($park)){
            $this->error('获取失败','park_list');
        }

        //产业链 城市 行业 list
        $label =new Label();
        $city=$label->city_list();
        $chain=$label->chain(0);
        $industry=$label->industry(0);


        $city_name=db('city')->whereIn('id',[$park['city_id'],$park['area_id']])->column('city_name','id');
        $chain_ids=db('parks_chain')->where(['status'=>1,'park_id'=>$id])->order('chain_id','asc')->column('chain_id');
        $park_chian=db('chain')->where('status',1)->whereIn('id',$chain_ids)->column('chain_name');
        $industry_ids=db('parks_industry')->where(['status'=>1,'park_id'=>$id])->order('industry_id','asc')->column('industry_id');
        $park_industry=db('industry')->where('status',1)->whereIn('id',$industry_ids)->column('industry_name');

        $chain_str=implode('@',$park_chian);
        $industry_str=implode('@',$park_industry);
        $chain_industry=[
            'chain_ids'=>$chain_ids,
            'chain_str'=>$chain_str,
            'industry_ids'=>$industry_ids,
            'industry_str'=>$industry_str
        ];
        unset($chain_ids,$park_chian,$industry_ids,$park_industry);
        $this->assign([
            'park'=>$park,
            'chain'=>$chain,
            'city'=>$city,
            'industry'=>$industry,
            'city_name'=>$city_name,
            'ci'=>$chain_industry
        ]);
        return $this->fetch('detail');
    }

    /**
     * 园区编辑
     */
    public function edit(Request $request)
    {
        $data=$this->request->post();

        /****city_str*****/
        $city=array($data['province_id'],$data['city_id'],$data['area_id']);
        $city_str=[];
        $cityModel=db('city');
        foreach ($city as $id){
            if (!empty($id)){
                $name=$cityModel->where('id',$id)->value('city_name as name');
                $city_str[]=compact('id','name');
            }
        }
        $city_name=array_column($city_str,'name');
        $data['city']=$data['province']= isset($city_name[0]) ? $city_name[0] : '';
        $data['p_city']=isset($city_name[1]) ? $city_name[1] : '';
        $data['district']=isset($city_name[2]) ? $city_name[2] : '';
        /****industry_str*****/
        $industry_str=[];
        $industry_ids=[];
        $industry_data=$request->post()['industry'];
        $industryModel=db('industry');
        foreach ($industry_data as $id){
            if ($id){
                $name=$industryModel->where('id',$id)->value('industry_name as name');
                $industry_str[]=compact('id','name');
                array_push($industry_ids,$id);
            }
        }
        /****chain****/
        $chain_data=$request->post()['chain'];
        $chains=[];
        foreach ($chain_data as $chain_id){
            if ($chain_id){
                array_push($chains,$chain_id);
            }
        }
        unset($data['chain'],$data['industry']);

        $data['city_str']=serialize($city_str);
       // dd($industry_str);
        if (!empty($industry_str)){
            $data['prime_mover_industry']=implode('@',array_column($industry_str,'name'));
        }

        $chainInsert=[];
        $industryInsert=[];
        Db::startTrans();
        try {
            /****主表****/
            Db::table('yd_parks')->where('id',$data['id'])->update($data);
            /****chain****/
            if (!empty($chains)){
                Db::table('yd_parks_chain')->where(['status'=>1,'park_id'=>$data['id']])->update(['status'=>-1]);
                foreach ($chains as $k=>$id){
                    $chainInsert[$k]['park_id']=$data['id'];
                    $chainInsert[$k]['chain_id']=$id;
                    $chainInsert[$k]['status']=1;
                }
                Db::table('yd_parks_chain')->insertAll($chainInsert);
            }
            /****industry****/
            if (!empty($industry_ids)){
                Db::table('yd_parks_industry')->where(['status'=>1,'park_id'=>$data['id']])->update(['status'=>-1]);
                foreach ($industry_ids as $k=>$id){
                    $industryInsert[$k]['park_id']=$data['id'];
                    $industryInsert[$k]['industry_id']=$id;
                    $industryInsert[$k]['status']=1;
                }
                Db::table('yd_parks_industry')->insertAll($industryInsert);
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->error('修改失败','park_list');
        }
        $this->success('修改成功','park_list');
    }

    /**
     * 删除
     */
    public function del(Request $request){
        $id=$request->get('id',null,'intval');
        Db::startTrans();
        try {
            Db::table('yd_parks')->where(['status'=>1,'id'=>$id])->update(['status'=>-1]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $msg  = "File：" . $e->getFile() . "\n";
            $msg .= "Line：" . $e->getLine() . "\n";
            $msg .= "Message：" . $e->getMessage() . "\n";
            var_dump($msg);
            // 回滚事务
            Db::rollback();
            $this->error('删除失败','park_list');
        }
        $this->success('删除成功','park_list');
    }


    /**
     * 添加园区工商数据
     * @return mixed
     */
    public function add_business(Request $request)
    {
        $park_id=$request->get('park_id',0,'intval');
        if ($request->isPost()){
            if (!$park_id){
                $this->error('添加失败','add_business');
            }
            /****industry_str*****/
            $industry_name=[];
            $industry_data=$request->post()['industry'];
            $industryModel=db('industry');
            foreach ($industry_data as $id){
                if ($id){
                    $name=$industryModel->where('id',$id)->value('industry_name as name');
                    array_push($industry_name,$name);
                }
            }
            $data=$request->post();
            $data['com_id']=$park_id;
            $data['industry']=implode('、',$industry_name);

            Db::startTrans();
            try {
                Db::table('yd_parks_business')->insert($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                $msg  = "File：" . $e->getFile() . "\n";
                $msg .= "Line：" . $e->getLine() . "\n";
                $msg .= "Message：" . $e->getMessage() . "\n";
                var_dump($msg);
                // 回滚事务
                Db::rollback();
                $this->error('添加失败','add_business',['park_id'=>$park_id]);
            }
            $this->success('添加成功','park_list');
        }
        $label =new Label();
        $industry=$label->industry(0);
        $this->assign('industry',$industry);
        return $this->fetch('addBusiness');
    }
}
